# -*- coding: utf-8 -*-
import os
import sys
import re
import click

def pick_up_chinese(path):
    print os.path.basename(path);
    # 读取文本
    file = open(path, "r" );
    content = "";
    for line in file.readlines():
        try:
            line = line.decode("utf-8");
            file_format = "utf-8";
        except Exception as e:
            line = line.decode("gbk");
            file_format = "gbk";
        content += line;
    file.close();

    # 取消掉单行和多行注释的影响
    content = re.sub(r"//.*[\r\n]+", "", content);
    content = re.sub(r"/\*[\s\S]*\*/", "", content);

    # 从文本中提取出引号之间的内容
    target_strings = [];
    target_strings += re.findall(r'".+?"', content);
    target_strings += re.findall(r"'.+?'", content);

    # 从找到的字符串中提取出包含中文字符的字符串
    chinese_words = [];
    for target_string in target_strings:
        if re.search(r"[^\x00-\xff]+", target_string):
            chinese_words.append(target_string.encode(file_format));

    # 去重并返回
    rtn = [];
    for chinese_word in chinese_words:
        if chinese_word not in rtn:
            rtn.append(chinese_word);
    return rtn;

@click.command()
@click.argument("target", nargs = -1)
@click.option("-i", "--inpath", type = str, default = None, help = u"要提取中文的路径")
def main(target, inpath):
    root_path = inpath;
    if inpath==None:
        root_path = os.getcwd();
    target_formats = list(target);

    if len(target_formats) == 0:
        print u"未指名目标文件类型";
        return;

    # 查找到需要处理的文件
    target_files_path = [];
    for dir_path, dirs, files in os.walk(root_path):
        for file in files:
            name, ext = os.path.splitext(file);
            for target_format in target_formats:
                if target_format == ext:
                    target_files_path.append(os.path.join(dir_path, file));
                    break;

    if len(target_files_path) == 0:
        print u"未找到需要处理的文件";
        return;

    # 把找到的文本写入文件
    export_file = open(os.path.join(root_path, "pick_up_chinese.txt" ), "w");
    for path in target_files_path:
        chinese_words = pick_up_chinese(path);
        if len(chinese_words)== 0:
            continue;
        export_file.write(os.path.basename(path) + "\n");
        for chinese_word in chinese_words:
            export_file.write("    " + chinese_word + "\n");
        export_file.write("\n");
    export_file.close();

if __name__ == '__main__':
    main();